from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
import logging

_logger = logging.getLogger(__name__)


class DingTalkDepartment(models.Model):
    _name = 'dingtalk.department'
    _description = '钉钉部门'
    _rec_name = 'name'
    _order = 'dept_id'
    
    name = fields.Char(string="部门名称", required=True)
    dept_id = fields.Char(string="钉钉部门ID", required=True, index=True,
                         help="钉钉系统中的部门ID")
    parent_id = fields.Many2one('dingtalk.department', string="上级部门", 
                               index=True, ondelete='cascade')
    child_ids = fields.One2many('dingtalk.department', 'parent_id', string="子部门")
    
    # 部门信息
    order_num = fields.Integer(string="排序", default=0)
    create_dept_group = fields.Boolean(string="自动创建群", 
                                      help="是否同步创建一个关联此部门的企业群")
    auto_add_user = fields.Boolean(string="自动入群",
                                   help="当部门有新人时，是否会自动加入部门群")
    
    # 员工统计
    employee_ids = fields.One2many('dingtalk.employee', 'department_id', string="部门员工")
    employee_count = fields.Integer(string="员工数", compute='_compute_employee_count', store=True)
    
    # 同步信息
    last_sync_time = fields.Datetime(string="最后同步时间", readonly=True)
    sync_status = fields.Selection([
        ('synced', '已同步'),
        ('error', '同步失败'),
        ('pending', '待同步'),
    ], string="同步状态", default='pending')
    
    active = fields.Boolean(string="启用", default=True)
    
    _sql_constraints = [
        ('dept_id_unique', 'UNIQUE(dept_id)', '钉钉部门ID必须唯一！'),
    ]
    
    @api.depends('employee_ids')
    def _compute_employee_count(self):
        """计算员工数量"""
        for record in self:
            record.employee_count = len(record.employee_ids)
    
    @api.model
    def sync_from_dingtalk(self):
        """从钉钉同步部门架构"""
        config = self.env['dingtalk.config'].get_default_config()
        access_token = config.get_valid_access_token()
        api = config._get_api_client()
        
        _logger.info("=" * 80)
        _logger.info("开始同步钉钉部门架构...")
        
        # 获取所有部门
        departments = api.get_all_departments(access_token)
        _logger.info(f"从钉钉获取到 {len(departments)} 个部门")
        
        created_count = 0
        updated_count = 0
        error_count = 0
        
        # 先创建或更新所有部门（不设置父部门）
        dept_map = {}  # {dingtalk_dept_id: odoo_record}
        
        for dept_data in departments:
            try:
                dept_id = str(dept_data['dept_id'])
                
                # 查找是否已存在
                existing = self.search([('dept_id', '=', dept_id)], limit=1)
                
                vals = {
                    'name': dept_data['name'],
                    'dept_id': dept_id,
                    'order_num': dept_data.get('order', 0),
                    'create_dept_group': dept_data.get('create_dept_group', False),
                    'auto_add_user': dept_data.get('auto_add_user', False),
                    'last_sync_time': fields.Datetime.now(),
                    'sync_status': 'synced',
                }
                
                if existing:
                    existing.write(vals)
                    dept_map[dept_id] = existing
                    updated_count += 1
                    _logger.info(f"  ✅ 更新部门: {dept_data['name']} (ID: {dept_id})")
                else:
                    new_dept = self.create(vals)
                    dept_map[dept_id] = new_dept
                    created_count += 1
                    _logger.info(f"  ✨ 创建部门: {dept_data['name']} (ID: {dept_id})")
                    
            except Exception as e:
                error_count += 1
                _logger.error(f"  ❌ 处理部门失败 {dept_data.get('name')}: {str(e)}")
        
        # 第二遍：设置父子关系
        _logger.info("设置部门层级关系...")
        for dept_data in departments:
            try:
                dept_id = str(dept_data['dept_id'])
                parent_id = str(dept_data.get('parent_id', ''))
                
                if parent_id and parent_id != '1' and dept_id in dept_map:
                    if parent_id in dept_map:
                        dept_map[dept_id].write({
                            'parent_id': dept_map[parent_id].id
                        })
                        _logger.info(f"  🔗 设置层级: {dept_data['name']} -> {dept_map[parent_id].name}")
                        
            except Exception as e:
                _logger.error(f"  ❌ 设置层级关系失败: {str(e)}")
        
        # 更新配置统计
        config.sudo().write({
            'last_sync_time': fields.Datetime.now(),
            'total_departments': len(dept_map),
        })
        
        _logger.info("=" * 80)
        _logger.info(f"✅ 部门同步完成！")
        _logger.info(f"  创建: {created_count}")
        _logger.info(f"  更新: {updated_count}")
        _logger.info(f"  失败: {error_count}")
        _logger.info(f"  总计: {len(dept_map)}")
        _logger.info("=" * 80)
        
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('同步完成'),
                'message': _('成功同步 %d 个部门（创建 %d，更新 %d）') % (
                    len(dept_map), created_count, updated_count
                ),
                'type': 'success',
                'sticky': False,
            }
        }
    
    def action_sync_employees(self):
        """同步当前部门的员工"""
        self.ensure_one()
        return self.env['dingtalk.employee'].sync_department_employees(self.dept_id)

